package com.buss.core.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.buss.core.dao.OrganizationDao;
import com.buss.core.model.Organization;
import com.buss.core.persistence.OrderBy;
import com.buss.core.persistence.ResultList;
import com.buss.core.service.OrganizationService;

@Service
public class OrganizationServiceImpl implements OrganizationService {

	private static final long serialVersionUID = -1853807924878964146L;
	
	@Autowired
	private OrganizationDao organizationDao;

	public void deleteOrganization(Long[] ids) {
		for(Long id : ids){
			Organization organization = organizationDao.loadOrganization(id);
			if(organization == null){
				return ;
			}
			if(organization.getParentId() != 0){
				Organization pOrgan = organizationDao.loadOrganization(organization.getParentId());
				organizationDao.updateNodeNum(pOrgan.getId(), 1);
			}
		}
		organizationDao.deleteOrganization(ids);
	}

	public void editOrganization(Organization organization) {
		Organization tmpOrgan = organizationDao.loadOrganization(organization.getParentId());
		if(tmpOrgan != null && !(organization.getParentId().equals(tmpOrgan.getParentId()))){
			if(organization.getParentId() != 0){
				organizationDao.updateNodeNum(organization.getParentId(), -1);
			}
			if(tmpOrgan.getParentId() != 0){
				organizationDao.updateNodeNum(tmpOrgan.getParentId(), 1);
			}
		}
		organizationDao.editOrganization(organization);
	}

	public Organization loadOrganization(Long id) {
		return organizationDao.loadOrganization(id);
	}

	public Organization mergeOrganization(Organization organization) {
		if(organization == null) return null;
		if(organization.getId() != null){
			Organization tmpOrgan = organizationDao.loadOrganization(organization.getParentId());
			if(tmpOrgan != null && organization.getParentId() != tmpOrgan.getParentId()){
				if(organization.getParentId() != 0){
					organizationDao.updateNodeNum(organization.getParentId(), -1);
				}
				if(tmpOrgan.getParentId() != 0){
					organizationDao.updateNodeNum(tmpOrgan.getParentId(), 1);
				}
			}
		}else{
			organization.setNodeNum(0L);
		}
		return organizationDao.mergeOrganization(organization);
	}

	public ResultList<Organization> queryByParentId(String companyId,Long parentId,OrderBy orderBy) {		
		return organizationDao.queryByParentId(companyId,parentId,orderBy);
	}

	public void saveOrganization(Organization organization) {
		if(organization.getParentId() != 0){
			organizationDao.updateNodeNum(organization.getParentId(), -1);
		}
		organization.setNodeNum(0L);
		organizationDao.saveOrganization(organization);
	}

}
